package com.suxin.splitter.spring;

import com.suxin.splitter.MethodExecutor;
import com.suxin.splitter.ParamSplitter;
import com.suxin.splitter.ResultMerger;

import java.util.List;
import java.util.function.Function;

/**
 * @author Tang
 * @classname DefaultSplitService
 * @description [  ]
 * @date 2022/11/10 17:15
 */
public class DefaultSplitService<P,R> implements SplitService<P,R>{

    private final ParamSplitter<P> paramSplitter;
    private final MethodExecutor methodExecutor;
    private final ResultMerger<R> resultMerger;

    public DefaultSplitService(ParamSplitter<P> paramSplitter,
                               MethodExecutor methodExecutor,
                               ResultMerger<R> resultMerger) {
        this.paramSplitter = paramSplitter;
        this.methodExecutor = methodExecutor;
        this.resultMerger = resultMerger;
    }

    @Override
    public R split(Function<P, R> function, P p, int maxSize) {
        List<P> params = this.paramSplitter.split(p, maxSize);
        List<R> results = null;
        try {
            results = this.methodExecutor.execute(function, params);
        } catch (Exception e) {
            e.printStackTrace();
        }
        R result = this.resultMerger.merge(results);
        return result;
    }
}
